﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Lamex.mPPC.Common
{
    public sealed class SerialNoHelper
    {
        private static volatile SerialNoHelper helper;
        private static readonly Object syncRoot = new Object();

        private static String lastdate;
        private static Int32 lastno;

        public SerialNoHelper()
        {
        }
        public static SerialNoHelper Helper
        {
            get
            {
                if (helper == null)
                {
                    lock (syncRoot)
                    {
                        if (helper == null)
                            helper = new SerialNoHelper();
                    }
                }
                return helper;
            }
        }
        /// <summary>
        /// 生成流水号
        /// </summary>
        /// <param name="serialno">从数据库读取最大的流水号</param>
        /// <returns></returns>
        public String Generate(String serialno)
        {
            lock (syncRoot)
            {
                var today = DateTime.Today.ToString("yyMMdd");

                if (today == lastdate)
                   // return $"MES{today}{++lastno:00000}"; --vs2015以上版本
                   return string.Format("{0}{1}", today, (++lastno).ToString().PadLeft(5, '0'));

                lastdate = today;
                lastno = 0;
                if (!String.IsNullOrEmpty(serialno) && serialno.Substring(0, 6) == today)
                    lastno = Convert.ToInt32(serialno.Substring(6));

                // return $"MES{today}{++lastno:00000}";
                return string.Format("{0}{1}", today, (++lastno).ToString().PadLeft(5, '0'));

            }
        }      
    }
}
